﻿using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LX.NHibernate.Data
{
    public class DbFactory
    {
        public static ISessionFactory SessionFactory;
        private static ISession currentSession;
        private static object lockHelper = new object();
        public DbFactory()
        {
            ISessionFactory sessionFactory = new Configuration().Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/Config/teamcity-hibernate.cfg.xml").BuildSessionFactory();
        }
        public static ISession GetCurrentSession2()
        {
            if (currentSession == null)
            {
                lock (lockHelper)
                {
                    currentSession = SessionFactory.OpenSession();
                }
            }

            return currentSession;
        }
        public static ISessionFactory GetCurrentSession()
        {
            //第一种写法（加载指定的文件）
            ISessionFactory sessionFactory = new Configuration().Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/Config/teamcity-hibernate.cfg.xml").BuildSessionFactory();

            return sessionFactory;

            //using (ISession session = sessionFactory.OpenSession())
            //{
            //    return session;
            //}

            //第二种(暂没有成功)
            //Configuration cfg = new Configuration().AddAssembly("hibernate-configuration");       //Model为映射文件所在程序集名称
            //ISessionFactory sessionFactory = cfg.BuildSessionFactory();
            //return sessionFactory;

            //第二种(加载bin文件下面的文件)
            //Configuration cfg = new Configuration();
            //cfg.Configure();
            //return cfg.BuildSessionFactory();
        }
    }
}
